package com.starblink.android.guang.activeconfig.ui

import android.os.CountDownTimer
import android.os.Handler
import android.os.Message
import androidx.lifecycle.viewModelScope
import com.kunminx.architecture.domain.message.MutableResult
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.log.SKLogger
import com.starblink.preferenceconfig.bean.PreferenceBrand
import com.starblink.rocketreserver.FetchSiteQuery
import com.starblink.rocketreserver.ListPreferenceConfigQuery
import com.starblink.rocketreserver.fragment.SiteVOF
import com.starblink.rocketreserver.type.SiteRequest
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class ActiveConfigVM : BaseViewModel() {
    companion object {
        const val MSG_HANDLE_RESPONSE: Int = 100
    }

    val goToMainPageLD = MutableResult.Builder<String?>().setAllowNullValue(true).create()
    val goToBrandPreferencePageLD = MutableResult<List<PreferenceBrand>>()

    /**
     * 跳转偏好页面
     */
    fun gotoBrandPreferencePage(preferenceBrands: List<PreferenceBrand>) {
        SKLogger.e("dss2", "跳转到偏好选择页面")
        goToBrandPreferencePageLD.value = preferenceBrands
    }

    /**
     * 跳转到主页
     */
    fun gotoMainPage(jumpUrl: String? = null ) {
        SKLogger.e("dss2", "跳转到首页")
        goToMainPageLD.value = jumpUrl
    }

    var timeOutCountDownTimer: CountDownTimer = object : CountDownTimer(4000, 4000) {
        override fun onTick(millisUntilFinished: Long) {}

        override fun onFinish() {
            SKLogger.e("dss", "timeOutCountDownTimer-onFinish")
            isRequestTimeOut = true
            mHandler.removeCallbacksAndMessages(null)
            gotoMainPage()
        }
    }
    var isRequestTimeOut = false // 是否已超时
    val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == MSG_HANDLE_RESPONSE) {
                // 仅当请求未超时时，处理返回结果
                if (!isRequestTimeOut) {
                    timeOutCountDownTimer.cancel()
                    (msg.obj as? List<PreferenceBrand>)?.let {
                        // 跳转到品牌偏好页面
                        gotoBrandPreferencePage(it)
                    } ?: run {
                        // 请求失败
                        gotoMainPage()
                    }
                }
            }
        }
    }

    /**
     * 加载偏好品牌列表
     */
    fun loadPreferenceBrands() {
        viewModelScope.launch {
            // 启动超时倒计时
            isRequestTimeOut = false
            timeOutCountDownTimer.start()

            // 获取品牌偏好列表
            val response = SkGqlClient.skQuery(
                ListPreferenceConfigQuery(type = 1)
            )?.data?.listPreferenceConfig?.filter { it?.id != null }
                ?.map { PreferenceBrand(it!!) }
            // 注意：虽然超时倒计时和请求协程都运行在主线程中，但是存在同步问题。两者通过使用Handler保证代码同步。
            mHandler.sendMessage(Message.obtain(mHandler, MSG_HANDLE_RESPONSE, response))
        }
    }

    /**
     *
    # 站点信息
    type SiteVO {
    # 站点类型 1：欧洲 2：美国
    type: Int

    # 站点code（us,eu）
    code: String

    # 国家简码
    countryCode: String
    }
     */
    fun getSite(siteCallBack: ((site: SiteVOF?) -> Unit)) {
        viewModelScope.async {
            val response = SkGqlClient.skQuery(
                FetchSiteQuery(
                    param = SiteRequest()
                ),
                showFailToast = false,
                showErrorToast = false
            )

            if (response?.data?.fetchSite == null) {
                siteCallBack.invoke(null)
            } else {
                siteCallBack.invoke(response.data!!.fetchSite.siteVOF)
            }
        }
    }
}